<template>
  <CustomerLayout>
    <div class="favorite-foods-container">
      <!-- 页面装饰背景 -->
      <div class="page-decoration">
        <div class="floating-shapes">
          <div class="shape shape-1"></div>
          <div class="shape shape-2"></div>
          <div class="shape shape-3"></div>
          <div class="shape shape-4"></div>
          <div class="shape shape-5"></div>
        </div>
      </div>

      <!-- 页面标题 -->
      <div class="page-header">
        <div class="title-wrapper">
          <div class="title-icon">🍕</div>
          <h1 class="main-title">我的收藏商品</h1>
          <div class="title-decoration"></div>
        </div>
        <div class="subtitle">品尝你心仪的美食佳肴</div>
        <div class="stats-bar">
          <div class="stat-item">
            <span class="stat-number">{{ total }}</span>
            <span class="stat-label">个商品</span>
          </div>
          <div class="stat-divider"></div>
          <div class="stat-item">
            <span class="stat-number">{{ currentPage }}</span>
            <span class="stat-label">/ {{ totalPages || 1 }} 页</span>
          </div>
        </div>
      </div>
      
      <!-- 商品列表 -->
      <div v-if="foods.length > 0" class="food-list">
        <div v-for="food in foods" :key="food.id" class="food-item">
          <div class="food-image" @click="goToFood(food.id)">
            <el-image 
              :src="food.image" 
              fit="cover"
              :lazy="true"
              :preview-src-list="[food.image]"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <!-- 商品状态遮罩 -->
            <div v-if="(food as any).status === 'OFF_SHELF'" class="food-status-overlay">
              <span class="status-text">已下架</span>
            </div>
          </div>
          
          <div class="food-content" @click="goToFood(food.id)">
            <div class="food-name">{{ food.name }}</div>
            
            <div v-if="food.description" class="food-description">
              {{ food.description }}
            </div>
            
            <div class="food-store" v-if="food.storeName">
              来自: {{ food.storeName }}
            </div>
            
            <div class="food-stats">
              <div class="rating">
                <el-rate 
                  v-model="food.rating" 
                  disabled 
                  text-color="#ff9900"
                  :show-score="true"
                  score-template="{value}"
                />
              </div>
              <div class="sales">月售 {{ (food as any).sales || food.monthlySales }}+</div>
            </div>
            
            <div class="food-price">
              <span class="current-price">¥{{ (food.price || 0).toFixed(2) }}</span>
              <span v-if="food.originalPrice && food.originalPrice > 0" class="original-price">
                ¥{{ food.originalPrice.toFixed(2) }}
              </span>
            </div>
          </div>
          
          <div class="food-actions">
            <el-button 
              type="danger" 
              circle 
              @click.stop="removeFavorite(food.id)"
              :loading="removingId === food.id"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="!loading" class="empty-state-wrapper">
        <div class="empty-decoration">
          <div class="empty-icon">🍽️</div>
          <div class="empty-title">还没有收藏的商品</div>
          <div class="empty-subtitle">快去发现你心仪的美食佳肴吧～</div>
          <div class="empty-actions">
            <el-button type="primary" size="large" @click="goToHome" class="explore-btn">
              <span>🔍</span>
              开始探索
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
        <el-skeleton :rows="3" animated style="margin-top: 20px" />
      </div>
      
      <!-- 分页 -->
      <div v-if="foods.length > 0 && totalPages > 1" class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="total"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </CustomerLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Picture } from '@element-plus/icons-vue';
import CustomerLayout from '@/components/customer/CustomerLayout.vue';
import { favoriteApi, storeApi } from '@/api/customer';
import { Food } from '@/types/customer';

const router = useRouter();
const loading = ref(false);
const removingId = ref<number | null>(null);

// 商品列表状态
const foods = ref<Food[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const totalPages = ref(0);

// 获取收藏的商品列表
const fetchFavoriteFoods = async (page = 1) => {
  try {
    loading.value = true;
    // 根据接口文档和API响应结构，使用正确的参数格式
    const res = await favoriteApi.getFavoriteFoods({ 
      page: page,
      size: pageSize.value 
    }) as any;
    
    console.log('收藏商品API响应:', res);
    
    // 根据实际API响应结构解析数据
    let foodsData: any[] = [];
    let totalElements = 0;
    let totalPagesFromAPI = 1;
    
    if (res && res.data) {
      // 标准分页响应格式: {status, message, data: {content, totalElements, ...}}
      if (res.data.data && Array.isArray(res.data.data.content)) {
        // 嵌套格式
        foodsData = res.data.data.content;
        totalElements = res.data.data.totalElements || 0;
        totalPagesFromAPI = res.data.data.totalPages || 1;
      } else if (Array.isArray(res.data.content)) {
        // 直接分页格式
        foodsData = res.data.content;
        totalElements = res.data.totalElements || 0;
        totalPagesFromAPI = res.data.totalPages || 1;
      } else if (Array.isArray(res.data)) {
        // 直接数组格式
        foodsData = res.data;
        totalElements = res.data.length;
        totalPagesFromAPI = 1;
      }
    }
    
    console.log('解析的商品数据:', foodsData);
    console.log('总数:', totalElements, '总页数:', totalPagesFromAPI);
    
    // 确保 foodsData 是数组
    if (!Array.isArray(foodsData)) {
      console.warn('foodsData 不是数组，设置为空数组');
      foodsData = [];
    }
    
    // 对每个商品获取店铺名称
    const processedFoods = await Promise.all(
      foodsData.map(async (food: any) => {
        const processedFood = {
          ...food,
          // 确保必要字段存在
          id: food.id,
          name: food.name || '未知商品',
          price: food.price || 0,
          description: food.description || '',
          image: food.image || '/images/food.png',
          status: food.status || 'ON_SHELF',
          storeId: food.storeId || 0,
          sales: food.sales || 0,
          monthlySales: food.sales || 0, // 使用sales作为月销量
          rating: 4.5, // 默认评分，可以后续通过API获取
          storeName: '加载中...' // 默认店铺名称
        };

        // 如果有店铺ID，尝试获取店铺名称
        if (food.storeId) {
          try {
            // 调用获取店铺详情API获取店铺名称
            const storeRes = await storeApi.getStoreDetail(food.storeId.toString());
            if (storeRes && storeRes.data) {
              // 处理可能的嵌套响应结构
              const storeData = storeRes.data.data || storeRes.data;
              processedFood.storeName = storeData.name || `店铺 ${food.storeId}`;
            } else {
              processedFood.storeName = `店铺 ${food.storeId}`;
            }
          } catch (error) {
            console.warn(`获取店铺 ${food.storeId} 信息失败:`, error);
            processedFood.storeName = `店铺 ${food.storeId}`;
          }
        }

        return processedFood;
      })
    );
    
    // 更新数据
    foods.value = processedFoods;
    total.value = totalElements;
    totalPages.value = totalPagesFromAPI;
    
    console.log('处理后的商品列表:', foods.value);
    
  } catch (error) {
    console.error('获取收藏商品失败:', error);
    ElMessage.error('获取收藏商品列表失败');
    foods.value = [];
  } finally {
    loading.value = false;
  }
};

// 前往商品详情页 - 增加状态检查
const goToFood = (foodId: number) => {
  // 查找商品信息以检查状态
  const food = foods.value.find(f => f.id === foodId) as any;
  if (food && food.status && food.status === 'OFF_SHELF') {
    ElMessage.warning('商品已下架');
    return;
  }
  
  // 根据商品所属店铺跳转到店铺详情页，并定位到商品
  if (food && food.storeId) {
    router.push(`/customer/store/${food.storeId}?foodId=${foodId}`);
  } else {
    // 如果没有店铺信息，跳转到商品详情页
    router.push(`/customer/food/${foodId}`);
  }
};

// 前往首页
const goToHome = () => {
  router.push('/customer');
};

// 处理页面变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchFavoriteFoods(page);
};

// 取消收藏
const removeFavorite = (foodId: number) => {
  ElMessageBox.confirm(
    '确定要取消收藏该商品吗?',
    '取消收藏',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      removingId.value = foodId;
      // 调用取消收藏 API
      await favoriteApi.removeFavoriteFood(foodId);
      ElMessage.success('已取消收藏');
      
      // 参考微信小程序实现，取消收藏后重新加载数据
      // 这样可以确保分页信息的准确性
      await fetchFavoriteFoods(1);
      currentPage.value = 1;
      
    } catch (error) {
      console.error('取消收藏失败:', error);
      ElMessage.error('取消收藏失败');
    } finally {
      removingId.value = null;
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 组件挂载时获取收藏商品列表
onMounted(() => {
  fetchFavoriteFoods();
});
</script>

<style scoped>
.favorite-foods-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  position: relative;
  min-height: 100vh;
}

/* 页面装饰背景 */
.page-decoration {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: -1;
  overflow: hidden;
}

.floating-shapes {
  position: relative;
  width: 100%;
  height: 100%;
}

.shape {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
  animation: float 6s ease-in-out infinite;
}

.shape-1 {
  width: 120px;
  height: 120px;
  background: linear-gradient(45deg, #ff6b6b, #ee5a24);
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 80px;
  height: 80px;
  background: linear-gradient(45deg, #4ecdc4, #00b894);
  top: 20%;
  right: 15%;
  animation-delay: 2s;
}

.shape-3 {
  width: 100px;
  height: 100px;
  background: linear-gradient(45deg, #45b7d1, #74b9ff);
  bottom: 30%;
  left: 5%;
  animation-delay: 4s;
}

.shape-4 {
  width: 60px;
  height: 60px;
  background: linear-gradient(45deg, #96ceb4, #00cec9);
  bottom: 15%;
  right: 20%;
  animation-delay: 1s;
}

.shape-5 {
  width: 90px;
  height: 90px;
  background: linear-gradient(45deg, #ffeaa7, #fdcb6e);
  top: 50%;
  right: 5%;
  animation-delay: 3s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 页面标题区域 */
.page-header {
  margin-bottom: 24px;
  text-align: center;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(248, 249, 250, 0.9));
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 20px 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.title-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 8px;
  position: relative;
}

.title-icon {
  font-size: 32px;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

.main-title {
  font-size: 28px;
  font-weight: 800;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

.title-decoration {
  width: 3px;
  height: 40px;
  background: linear-gradient(to bottom, #667eea, #764ba2);
  border-radius: 2px;
  animation: slideUp 1s ease-out;
}

@keyframes slideUp {
  from {
    height: 0;
  }
  to {
    height: 40px;
  }
}

.subtitle {
  font-size: 16px;
  color: #666;
  margin-bottom: 16px;
  font-weight: 500;
  opacity: 0.8;
}

.stats-bar {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 12px;
  padding: 10px 20px;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #2c3e50;
}

.stat-label {
  font-size: 13px;
  color: #7f8c8d;
  font-weight: 500;
}

.stat-divider {
  width: 1px;
  height: 24px;
  background: linear-gradient(to bottom, transparent, #ddd, transparent);
}

.food-list {
  margin-bottom: 20px;
}

.food-item {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
  /* 添加彩色边框装饰 */
  border-left: 4px solid transparent;
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1, #96ceb4, #ffeaa7);
  background-origin: border-box;
  background-clip: padding-box, border-box;
  transition: all 0.3s ease;
}

.food-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  border-left-width: 6px;
}

.food-item:nth-child(5n+1) {
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #ff6b6b, #ee5a24);
}

.food-item:nth-child(5n+2) {
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #4ecdc4, #00b894);
}

.food-item:nth-child(5n+3) {
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #45b7d1, #74b9ff);
}

.food-item:nth-child(5n+4) {
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #96ceb4, #00cec9);
}

.food-item:nth-child(5n+5) {
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #ffeaa7, #fdcb6e);
}

.food-image {
  width: 100px;
  height: 100px;
  margin-right: 15px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
  cursor: pointer;
  position: relative;
}

.food-image .el-image {
  width: 100%;
  height: 100%;
}

.food-status-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
}

.status-text {
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.food-content {
  flex: 1;
  cursor: pointer;
}

.food-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.food-description {
  font-size: 13px;
  color: #666;
  margin-bottom: 5px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.food-store {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.food-stats {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.rating {
  margin-right: 15px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.sales {
  font-size: 12px;
  color: #999;
  font-weight: 500;
}

.food-price {
  margin-top: 5px;
}

.current-price {
  font-size: 18px;
  font-weight: bold;
  color: #e74c3c;
  margin-right: 8px;
}

.original-price {
  font-size: 14px;
  color: #95a5a6;
  text-decoration: line-through;
  font-weight: 500;
}

.food-actions {
  display: flex;
  align-items: center;
}

.loading-container {
  padding: 20px;
}

/* 空状态样式 */
.empty-state-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 60px 20px;
}

.empty-decoration {
  text-align: center;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(248, 249, 250, 0.9));
  backdrop-filter: blur(10px);
  border-radius: 30px;
  padding: 60px 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  max-width: 500px;
  width: 100%;
}

.empty-icon {
  font-size: 120px;
  margin-bottom: 30px;
  animation: bounce 2s ease-in-out infinite;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-20px);
  }
  60% {
    transform: translateY(-10px);
  }
}

.empty-title {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.empty-subtitle {
  font-size: 18px;
  color: #7f8c8d;
  margin-bottom: 40px;
  line-height: 1.6;
}

.empty-actions {
  margin-top: 30px;
}

.explore-btn {
  font-size: 18px;
  padding: 15px 30px;
  border-radius: 25px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.explore-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 35px rgba(102, 126, 234, 0.4);
}

.explore-btn span {
  margin-right: 8px;
  font-size: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 576px) {
  .food-item {
    flex-direction: column;
  }
  
  .food-image {
    width: 100%;
    height: 150px;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .food-actions {
    position: absolute;
    top: 15px;
    right: 15px;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
  }
}
</style>
